package com.wman.lib.utils.callback;

import android.text.TextUtils;

import com.orhanobut.logger.Logger;
import com.wman.sheep.BuildConfig;
import com.wman.sheep.common.application.AbsAppContext;
import com.wman.sheep.common.base.BaseEntity;
import com.wman.sheep.common.utils.GsonTool;
import com.wman.sheep.common.utils.TDevice;
import com.wman.sheep.common.utils.ToastUtil;
import com.wman.sheep.okgo.callback.AbsCallback;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

/**
 * JsonCallback 直接返回Json数据
 * todo 对异常的处理需要完善
 *
 * @param <T>
 */
public abstract class JsonCallback<T> extends AbsCallback<T> {

    private T clazz;

    public JsonCallback(T clazz) {
        this.clazz = clazz;
    }

    //该方法是子线程处理，不能做ui相关的工作
    @Override
    public T convertSuccess(Response response) throws IOException {
        String responseData = response.body().string();
        if (TextUtils.isEmpty(responseData)) return null;

        if (BuildConfig.DEBUG) {
            Logger.json(responseData);
        }

        if (clazz == null) {
            return (T) responseData;
        } else {
            return (T) GsonTool.parseOneFromJson(responseData, (Class<Object>) clazz);
        }
    }

    @Override
    public void onError(Call call, Response response, Exception e) {
        super.onError(call, response, e);

        if (0 == TDevice.getNetworkType()) {
            ToastUtil.showTextToast(AbsAppContext.resources().getString(com.wman.sheep.R.string.common_check_network));
        } else {
            ToastUtil.showTextToast(AbsAppContext.resources().getString(com.wman.sheep.R.string.common_net_error));
        }
    }

    @Override
    public void onAfter(T t, Exception e) {
        super.onAfter(t, e);
        try {
            BaseEntity entity = (BaseEntity) t;
            if (entity != null) {
                switch (entity.getCode()) {
                    case 0:
                        break;
                    case 1:
                        ToastUtil.showTextToast(AbsAppContext.resources().getString(com.wman.sheep.R.string.common_net_error));
                        break;
                    case 2:
                        ToastUtil.showTextToast(entity.getErrorMessage());
                        break;
                    case 10010001://未注册
                    case 10010002://登录失败
                    case 10010003://重新登录
                    case 10010004://token错误，不匹配
                    case 10010005://未设置token
                        ToastUtil.showTextToast("请重新登录...");
                        break;
                    case 10010006://重复请求接口
                    case 10030008:
                    default:
                        ToastUtil.showTextToast(entity.getErrorMessage() + "");
                        break;
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}